import { observable, action, toJS } from 'mobx';
import { Form } from 'weaver-mobile-page';

const initState = {
  extended: false,
  conditions: [],
  checkedGroups: [],
  mailContact: {
    id: '',
    mailUserName: '',
    mailAddress: '',
  },
};

export default class AddContactStore {
  
  @observable form = new Form.Store();
  @observable mailContact = initState.mailContact;
  @observable conditions = initState.conditions;
  @observable extended = initState.extended;
  @observable checkedGroups = initState.checkedGroups;


  @action
  handleCondition = (condition) => {
    if (!condition) return {};
    return this.loopCondition(condition, (c) => {
      const domkey = c.domkey.join('__');
      const req = { rules: 'required', viewAttr: 3 };
      const reqEmail = { rules: 'required|email', viewAttr: 3 };
      let field = { ...c };
      if (domkey === 'mailUserName') {
        field = { ...field, ...req };
      }
      if (domkey === 'mailAddress') {
        field = { ...field, ...reqEmail };
      }
      return field;
    });
  }

  loopCondition(condition, cb = () => {}) {
    if (Array.isArray(toJS(condition)) && condition.length > 0) {
      const loop = (conditioninfo) => {
        return conditioninfo.map(cb);
      };
      if (Array.isArray(toJS(condition[0].items))) {
        return condition.map((conditions) => ({ ...conditions, items: loop(conditions.items) }));
      } else {
        return loop(condition);
      }
    }
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    return this;
  }

  @action
  clear = () => this.setState(initState)
}
